<?php
/*
Plugin Name: Melative Entries
Plugin URI: http://tools.melative.com
Description: Loads API entry from melative
Version: 0.0.1
Author: Ryan Altman
Author URI: http://melative.com
*/

if( strpos($_SERVER['REQUEST_URI'], '/wp-admin/')!==false )
    return;

function init_melative_items() {
    wp_enqueue_script('google-jquery-min', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');
    wp_enqueue_script('melative-lib-js', '/' . PLUGINDIR . '/melative-item/js/lib.js');
}

add_action('init', 'init_melative_items');

$mela_domain        = 'http://melative.com/api/';
$mela_plugin_dir    = WP_PLUGIN_DIR . '/melative-item/';
$mela_entry_xsl     = $mela_plugin_dir . 'melative-entry.xsl';
$mela_kron_xsl      = $mela_plugin_dir . 'melative-kron.xsl';
$mela_library_xsl   = $mela_plugin_dir . 'melative-library.xsl';
$mela_lime_xsl      = $mela_plugin_dir . 'melative-lime.xsl';

function first_season_type($first, $season, $type)
{
    $v = array();
    if( $first ) $v[] = ucwords($first);
    if( $season ) $v[] = ucwords($season);
    if( $type ) $v[] = ucwords($type);
    
    return implode(', ', $v);
}

function description( $str )
{
    return preg_replace('/&lt;br \/&gt;/', '<br />', $str);
}

function allow_tags( $str, $depth=2 )
{
    while($depth>0)
    {
        $depth--;
    }
    
    return $str;
}

function melative_link_message( $text )
{
  $needles = array('/(^|[^"])(http:\/\/)([^\s"<>\/]{1,32})([^\s"<>]*?)($|[\s<>])/', '/(^|[^&;\w])@(\w{3,})@(\w+\.\w{2,4})?/', '/(^|[^&;\w])@(\w{3,})?/');
  $replace = array('\1<a href="\2\3\4">\2\3\4</a>\5', '\1@<a href="http://\3/\2">\2</a>', '\1@<a href="http://melative.com/\2">\2</a>');
  
  return preg_replace(
            $needles,
            $replace,
            $text);
}

function mela_kron_text( $text )
{
    if( preg_match_all('/tag:melative\.com,2007:([^:]+?):([^:]+?):([^:\s]*?) /', $text, $grp) )
    {
        for( $a=0; $a<count($grp); $a++ )
        {
            $url = $grp[1][$a];
            $disp= urldecode($grp[2][$a]);
            $attr= urldecode($grp[3][$a]);
            $repl= "<a rel=\"melative\" href=\"http://melative.com/{$url}\">{$disp}</a>" . (strlen($attr)>0 ? "({$attr})" : "");
            $text = str_replace($grp[0][$a], $repl, $text);
        }
    }
    
    return preg_replace('/\r?\n\s*\n+/', '</p><p>', $text);
}
                
function melative_transform( $m, $a )
{
    global $mela_domain;
    global $mela_plugin_dir;
    global $mela_entry_xsl;
    global $mela_library_xsl;
    global $mela_lime_xsl;
    global $mela_kron_xsl;
    
    // lime focus
    $lime_type = $m[1][$a];
    $lime_name = $m[2][$a];
    
    // user
    $user_name = $m[3][$a];
    $user_event= $m[4][$a];
    $user_sect = $m[5][$a];
    $user_ssect= $m[6][$a];
    
    if( strlen($lime_type)>0 )
    {
        // check for name splits
        if( strpos('/activity', $lime_name) )
        {
            $lime_name  = str_replace('/activity','',$lime_name);
            $url        = $mela_domain . "context/activity.xml?{$lime_type}={$lime_name}";
            $xsl        = $mela_entry_xsl;
            $exp        = 300;
        }
        else if ( strpos('/users', $lime_name) )
        {
            $lime_name  = str_replace('/users','',$lime_name);
            //$url        = $mela_domain . "context/activity.xml?{$lime_type}={$lime_name}";
            //$xsl        = $mela_entry_xsl;
            //$exp        = 300;
        }
        else
        {
            $url        = $mela_domain . "entity/metab.xml?{$lime_type}={$lime_name}&context_sections=:description:production";
            $xsl        = $mela_lime_xsl;
            $exp        = 259200;
        }
    }
    else if( strlen($user_name) )
    {
        if( strlen($user_event) )
        {
            // item 
            $url = "{$mela_domain}kronos/entry.xml?branch=ryan&user={$user_name}&entry_id={$user_event}";
            $xsl = $mela_kron_xsl;
            $exp = 43200;
        }
        else
        {
            switch($user_sect)
            {
                case 'stream':
                  $url = "{$mela_domain}user/stream.xml?user={$user_name}&{$user_ssect}";
                  $xsl = $mela_entry_xsl;
                  $exp = 600;
                  break;
                  
                case 'library':
                  $url = "{$mela_domain}library/{$user_name}.xml?context_type={$user_ssect}";
                  $xsl = $mela_library_xsl;
                  $exp = 1800;
                  break;
            }
        }
    }
    
    if( $url )
    {
        try
        {
            $xapi= new XSLFeed($url, $mela_plugin_dir ."cache/". md5($url) .".xml",$exp);
            return $xapi->output( $xsl, true );
        }
        catch( Exception $e )
        {
            echo "<!-- XSLFeed Exception: {$e->getMessage()} on url {$url} and {$xsl} -->";
        }
    }
    
    return false;
}

function handle_search( $obj )
{
    /*
    {
      "attr_media":"\/anime",
      "attr_meta_query":" year:2010 season:summer",
      "attr_string_query":"",
      "context":[
        {
          "attr_type":"anime",
          "attr_id":"34299",
          "type":"anime",
          "id":"34299",
          "image_url":"http:\/\/images.melative.com\/media_1lt2ha8aw5rlxsmv777j9yybeoboe8",
          "alias":[
            "Shiki",
            "\u5c4d\u9b3c"
           ],
          "meta":[
            {
              "attr_type":"length",
              "attr_value":"22"
             },
            {
              "attr_type":"first",
              "attr_value":"2010-07"
             },
            {
              "attr_type":"duration",
              "attr_value":"25m"
             },
            {
              "attr_type":"genre",
              "attr_value":"horror,
               mystery,
               supernatural"
             },
            {
              "attr_type":"theme",
              "attr_value":"vampires"
             },
            {
              "attr_type":"type",
              "attr_value":"series"
             },
            {
              "attr_type":"season",
              "attr_value":"summer"
             }
           ],
          "users":"4",
          "popularity":"41",
          "rank":"507"
         }
      }
    */
    
    $resp = "<div class=\"melative-search\">";
    
    
    
    foreach( $obj->context as $result )
    {
        $alias = is_array($result->alias) ? $result->alias[0] : $result->alias;
        $alias = str_replace('&', '&amp;', $alias);
        
        if( is_array( $result->alias ) )
        {
            unset($result->alias[0]);
            $aka = implode('<br />', $result->alias);
        }
        else
        {
            $aka = "";
        }
        
        $keywords = get_keywords( $result->meta );
        $first      = get_first_meta( $result->meta );
        
        $resp .=    "<div style=\"clear:left;\">".
                        "<h4>{$alias} <a rel=\"melative\" href=\"http://melative.com/{$result->type}/{$alias}\">Info</a></h4>".
                        "<img style=\"float:left;\" src=\"{$result->image_url}.96.jpg\" alt=\"None\" />\n".
                        "<div style=\"margin-left:116px;\"<strong>Starts:</strong> {$first}<br />".
                        (strlen($keywords)>0 ? "<strong>Keywords:</strong> {$keywords}<br />" : "").
                        (strlen($aka)>0 ? "<strong>Alternative names:</strong> {$aka}<br />" : "").
                    "</div><br class=\"clear\" /></div>\n";
    }
    
    $resp .= "</div>";
    
    return $resp;
}

function get_first_meta( $meta )
{
    foreach( $meta as $m )
    {
        if( $m->attr_type == 'first' )
            return $m->attr_value;
    }
}

function get_keywords( $meta )
{
    $kw = array();
    foreach( $meta as $m )
    {
        if( strpos( "-|genre|style|theme|mood|", $m->attr_type )>0 )
        {
            $kw[] = ucwords( $m->attr_value );
        }
    }
    
    return implode(', ', $kw);
}

function do_search( $type, $query )
{
    global $mela_plugin_dir;
    
    $url    = "http://melative.com/api/browseb.json?q={$query}&media={$type}&branch=ryan&limit=50";
    $cache  = $mela_plugin_dir . "cache/" . md5($url) . ".json";
    
    if( file_exists( $cache ) && (filemtime($cache)+600)<time() )
    {
        $api_resp = file_get_contents( $cache );
    }
    else
    {
        $api_resp = IO::curl( $url );
        if( strlen($api_resp)>0 )
        {
            file_put_contents( $cache, $api_resp );
        }
        else
        {
            return false;
        }
    }
    
    $api_obj = json_decode( $api_resp );
    
    if( $api_obj && !is_null($api_obj->context) )
    {
        return handle_search( $api_obj );
    }
    
    return false;
}

function melative_get_item( $d )
{    
  $types = 'anime|album|adrama|art|blog|character|comic|creator|event|film|lightnovel|literature|manga|music|periodical|stage|theatre|tv|vn';
  
  $search = '/<!--\s*http:\/\/melative\.com\/search\/('. $types .')\/(.+?)\s*-->/';
  
  if( preg_match_all( $search, $d, $matches ) )
  {
    require_once('class.xslfeed.php');
    $queries = array();
    for( $a=0; $a<count($matches[0]); $a++ )
    {
        $queries[] = array('match'=>$matches[0][$a], 'type'=>$matches[1][$a], 'query'=>$matches[2][$a]);
    }
    
    foreach( $queries as $q )
    {
        $res = do_search( $q['type'], $q['query'] );
        
        if( strlen($res) )
        {
            $d = str_replace( $q['match'], $res, $d );
        }
    }
  }
  
  $links = '/<!--\s*http:\/\/melative\.com\/(?(?='. $types .')(\w+)\/(.+?)|(\w+)\/(?(?=\d)(\d+)|(\w+)(?:\/(.+?))?))\s*-->/';

  if( preg_match_all( $links, $d, $matches ) )
  {
    //echo '<!--';
    //print_r($matches);
    //echo '-->';
    
    require_once('class.xslfeed.php');
    
    $c = count($matches[0]);
    for( $a=0; $a<$c; $a++ )
    {
      $html= melative_transform($matches, $a);
      $d = str_replace( $matches[0][$a], $html, $d );
    }
  }
  return $d;
}

add_filter('the_content', 'melative_get_item');

function melative_item_init() {
	wp_enqueue_style ('melative-item-css', '/' . PLUGINDIR . '/melative-item/plug.css');
}    
 
add_action('init', "melative_item_init");

?>
